package com.black.app.service.impl.my;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.black.app.domain.my.AppMyData;
import com.black.app.domain.my.AppMyDrinkDetail;
import com.black.app.domain.my.AppMyMenstrualDetail;
import com.black.app.domain.req.my.mydata.AppMyMenstrualDetailAddReq;
import com.black.app.service.my.AppMyMenstrualDetailService;
import com.black.app.mapper.my.AppMyMenstrualDetailMapper;
import com.black.common.exception.ServiceException;
import com.black.common.exception.database.RecordNotFoundException;
import com.black.common.utils.MessageUtils;
import com.black.common.utils.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
* @author 18494
* @description 针对表【app_my_menstrual_detail(经期详情表)】的数据库操作Service实现
* @createDate 2024-10-23 20:49:29
*/
@Service
public class AppMyMenstrualDetailServiceImpl extends ServiceImpl<AppMyMenstrualDetailMapper, AppMyMenstrualDetail>
    implements AppMyMenstrualDetailService{

    @Override
    public boolean addMenstrual(AppMyMenstrualDetailAddReq req) {
        // 1. 获取用户id
        req.setUserId(SecurityUtils.getAppLoginUser().getUserId());

        // 判断开始日期和结束日期是否正确
        if (req.getStartdate().after(req.getEnddate())) {
            throw new ServiceException(MessageUtils.message("app.my.menstrual.date.error"));
        }

        AppMyMenstrualDetail newEntity = new AppMyMenstrualDetail();
        BeanUtils.copyProperties(req, newEntity);

        boolean save = this.save(newEntity);

        return save;

    }

    @Override
    public PageInfo<AppMyMenstrualDetail> getMenstrual(AppMyMenstrualDetailAddReq req) {
        req.setUserId(SecurityUtils.getAppLoginUser().getUserId());
        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            this.baseMapper.getMenstrual(req);
        });
    }

    @Override
    public boolean deleteById() {
        //获取当前登录用户的用户id
        Long userId = SecurityUtils.getAppLoginUser().getUserId();
        // 删除MyMenstrualDetail表中id最大的数据并且userId等于当前登录用户的用户id
        int id = this.baseMapper.selectOne(new LambdaQueryWrapper<AppMyMenstrualDetail>()
                    .eq(AppMyMenstrualDetail::getUserId, userId)
                    .orderByDesc(AppMyMenstrualDetail::getId).last("limit 1")).getId();
        boolean result = this.removeById(id);
        return result;
    }
}




